package example.config;

import com.alibaba.fastjson.JSON;
import example.vo.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guoQ.z
 * @date 2020/12/15 16:52
 * TODO
 */
@RestControllerAdvice
public class BusinessExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity handlerBusinessException(BusinessException e) {
        return ResponseEntity.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handlerValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> errorList = new ArrayList<>(fieldErrors.size());
        fieldErrors.forEach(error -> {
            errorList.add(error.getDefaultMessage());
        });
        return ResponseEntity.fail(JSON.toJSONString(errorList));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity handlerException(Exception e) {
        return ResponseEntity.fail(e.getMessage());
    }
}
